package com.src.socket;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by shirenchuang on 2017/3/24.
 * 通信demo 客户端
 */
public class SocketClientT {


    public static void main(String[] args){

       // for(int i = 0 ;i <10;i++){
            connectSocket();
        //}

    }

    private static String readDataFromConsole() {
        Scanner scanner = new Scanner(System.in);
       // System.out.print(prompt);
        return scanner.nextLine();
    }

    public static void connectSocket(){

        try {
            while (true){
            Socket socket = new Socket("127.0.0.1",8089);


            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);

            printWriter.print(readDataFromConsole());
            printWriter.flush();
            socket.shutdownOutput();

            //获取输入流  读取服务端响应

            InputStream inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String str;
            StringBuffer sb = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {    //如果之前文件为空，则不执行输出
                sb.append(str);
            }
            System.out.print("我是客户端，服务端 回复："+sb.toString());


            //4、关闭资源
            bufferedReader.close();
            inputStream.close();
            printWriter.close();
            outputStream.close();
            socket.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
